package cn.schoolwow.quickdao.test.module.business.user.ddl.testcase;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.test.entity.Role;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.junit.Assert;

public class RenameTestCaseFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DAO dao = flowContext.checkInstanceData(DAO.class);

        dao.rebuild(Role.class);
        renameTableName(flowContext);
        renameTableColumnName(flowContext);
    }

    @Override
    public String name() {
        return "重命名表名和字段名测试用例";
    }

    private void renameTableName(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        Entity entity = dao.getEntity(Role.class);
        dao.renameTable(entity.tableName, entity.tableName+"_new");

        Assert.assertFalse(dao.hasTable(entity.tableName));
        Assert.assertTrue(dao.hasTable(entity.tableName+"_new"));

        dao.renameTable(entity.tableName+"_new", entity.tableName);
    }

    private void renameTableColumnName(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        Entity entity = dao.getEntity(Role.class);
        Property property = entity.getPropertyByFieldNameOrColumnName("roleName");

        dao.renameTableColumn(entity.tableName, property.column, property.column+"_new");

        Assert.assertFalse(dao.hasColumn(entity.tableName, property.column));
        Assert.assertTrue(dao.hasColumn(entity.tableName, property.column+"_new"));

        dao.renameTableColumn(entity.tableName, property.column+"_new", property.column);
    }
}
